#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include "pathdialog.h"

MainWindow::MainWindow(QString address,QWidget *parent)
    : currentAddress(address),QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->nearButton->hide();
    ui->changeButton->hide();
    ui->startlabel->hide();
    ui->endlabel->hide();
    ui->endComboBox->hide();
    ui->startComboBox->hide();

    ui->startComboBox->addItem(currentAddress);
    ui->endComboBox->addItem(currentAddress);
    ui->startComboBox->setEditable(true);
    ui->endComboBox->setEditable(true);

    mapWidget = findChild<MapWidget*>("mapwidget");

    // 添加加载提示
    QLabel* loadingLabel = new QLabel(this);
    loadingLabel->setText("Generating map...");
    loadingLabel->setAlignment(Qt::AlignCenter);
    loadingLabel->setStyleSheet("font: 20px; color: white; background: rgba(0,0,0,150);");
    loadingLabel->setGeometry(0, 0, width(), height());
    loadingLabel->show();

    // 连接地图生成完成信号到初始化逻辑
    connect(mapWidget, &MapWidget::mapGenerationComplete, this, [=]() {
        loadingLabel->deleteLater();
        bool ok;
        int centerId = address.toInt(&ok);
        if (ok) mapWidget->map.setCurrentcenter(QString::number(centerId));
        mapWidget->update(); // 强制重绘
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}




void MainWindow::on_searchButton_clicked()
{
    // 获取输入框内容
    QString input = ui->posInput->text().trimmed(); // 去除首尾空格

    if (input.startsWith("Node")) {
        bool ok;
        int id = input.mid(4).toInt(&ok);
        if (ok) {
            QPointF pos = mapWidget->map.getVertexPosition(id);
            mapWidget->map.findNear(pos.x(), pos.y(), 100);
            mapWidget->update();
            return;
        }
    }

}


void MainWindow::on_returnButton_clicked()
{
    // 重置地图显示状态（显示所有边）
    mapWidget->map.resetDisplay();

    // 重置视图参数（中心点和缩放）
    mapWidget->zoomLevel = 1.0; // 直接访问成员变量
    mapWidget->centerX = 500;  // 默认中心
    mapWidget->centerY = 500;

    // 根据currentAddress重新定位中心（如果需要）
    bool ok;
    int centerId = currentAddress.toInt(&ok);
    if (ok) {
        QPointF pos = mapWidget->map.getVertexPosition(centerId);
        mapWidget->centerX = pos.x();
        mapWidget->centerY = pos.y();
    }

    // 立即重绘
    mapWidget->update();
}


void MainWindow::on_abnearestButton_clicked()
{
    ui->posInput->hide();
    ui->searchButton->hide();
    ui->nearButton->show();
    ui->changeButton->show();
    ui->endlabel->show();
    ui->endComboBox->show();
    ui->startlabel->show();
    ui->startComboBox->show();

}


void MainWindow::on_homeButton_clicked()
{
    ui->posInput->show();
    ui->searchButton->show();
    ui->nearButton->hide();
    ui->changeButton->hide();
    ui->endlabel->hide();
    ui->endComboBox->hide();
    ui->startlabel->hide();
    ui->startComboBox->hide();
}


void MainWindow::on_changeButton_clicked()
{
    QString start=ui->startComboBox->currentText();
    QString end=ui->endComboBox->currentText();

    ui->startComboBox->setCurrentText(end);
    ui->endComboBox->setCurrentText(start);

}


void MainWindow::on_nearButton_clicked()
{
    QString start=ui->startComboBox->currentText().trimmed();
    QString end=ui->endComboBox->currentText().trimmed();


    ui->startComboBox->addItem(start);
    ui->endComboBox->addItem(end);
    // 1. 验证输入格式
    QRegularExpression nodeRegex("^Node\\d+$");
    if (!nodeRegex.match(start).hasMatch() || !nodeRegex.match(end).hasMatch()) {
        QMessageBox::warning(this, "错误", "请输入有效的节点编号（如Node123）");
        return;
    }

    // 2. 提取节点ID
    bool ok1, ok2;
    int startId = start.mid(4).toInt(&ok1); // 跳过"Node"前缀
    int endId = end.mid(4).toInt(&ok2);
    if (!ok1 || !ok2) {
        QMessageBox::warning(this, "错误", "节点编号格式错误");
        return;
    }

    // 3. 查找顶点对象
    Vertex* startVertex = nullptr;
    Vertex* endVertex = nullptr;
    for (auto v : mapWidget->map.getVertices()) {
        if (v->id == startId) startVertex = v;
        if (v->id == endId) endVertex = v;
    }
    if (!startVertex || !endVertex) {
        QMessageBox::warning(this, "错误", "节点不存在");
        return;
    }

    // 4. 调用Dijkstra算法
    std::unordered_map<Vertex*, double> dist;
    std::unordered_map<Vertex*, Edge*> prev;
    mapWidget->map.dijkstra(startVertex, dist, prev);

    // 5. 检查路径可达性
    if (dist.find(endVertex) == dist.end() || dist[endVertex] == std::numeric_limits<double>::infinity()) {
        QMessageBox::information(this, "提示", "两点之间不可达");
        return;
    }

    // 6. 反向追踪路径边
    std::vector<Edge*> pathEdges;
    Vertex* current = endVertex;
    while (current != startVertex) {
        if (prev.find(current) == prev.end()) break; // 防止死循环
        Edge* edge = prev[current];
        pathEdges.push_back(edge);
        current = (edge->start == current) ? edge->end : edge->start;
    }
    std::reverse(pathEdges.begin(), pathEdges.end());
    // 计算总长度
    double totalLength = 0;
    for (Edge* edge : pathEdges) {
        totalLength += edge->length;
    }

    // 显示弹窗
    PathDialog dialog(this, pathEdges, totalLength);
    dialog.exec();

    // 更新地图显示
    mapWidget->map.showAllEdges = false;
    mapWidget->map.visibleEdges = pathEdges;
    mapWidget->map.currentNearVertices = {startVertex, endVertex}; // 高亮起点终点
    mapWidget->update();
}


